<script setup lang='ts'>
  import { reactive, computed, watch } from 'vue';
  import { giftClassifyList } from '@/pinia/getter';
  import { propApi } from '@/api/controller'
  import { ToastWarning } from '@/utils/public';
  import Pagination from "../Pagination/index.vue";
  import xmImage from '../xmImage/index.vue';
  const props = defineProps({
    gift_id:{
      type:[Number,String],
      default:''
    },
    gift_type:{
      type:[Number,String],
      default:''
    },
    externalApi:{
      type:Boolean,
      default:false,
    },
    version:{
      type:String,
      default:'0.0.0'
    },
    show_gift_type:{
      type:Array<Number|String>,
      default:()=>[]
    },
    gift_info:{
      type:Object,
      default:()=>{}
    }
  })
  // watch(props,()=>{
  //   if(props.gift_id) action.gift_id = props.gift_id
  // })
  const gift_id = computed({
    set(val) {
      return val
    },
    get() {
      if(props.gift_id  && action.list.length == 0 && !action.getState) {
        if(props.version == '0.0.0') {
          getGiftList()
        }
        if(props.version == '0.0.1') {
          openSerachGift(false)
        }
      }
      
      return props.gift_id
    }
  })
  const $emit = defineEmits(['update:gift_id','update:gift_info','update:gift_image','getList'])
  const action = reactive({
    loading:false,
    // gift_id:'' as number | string,
    total:0,
    getState:false,
    options:[] as Array<any>,
    list:[] as Array<any>,
    newGiftList:[] as Array<any>,
    dialogFormVisible:false,
    giftClassifyList:[] as Array<any>,
    gift_name:'',
  })
  const initialQuyer = {
    page:1,
    limit:20,
    gift_id:'' as number | string,
    gift_name:'',
    gift_type:''
  }
  const listQuery = reactive({
    ...initialQuyer
  })
  const remoteMethod = async(query:any='')=>{
    if(query.length >= 1 && action.options.length == 0) {
      await getGiftList()
    }
    if(action.list.length > 0) {
      if(query.length >= 1) {
        const list = action.options.filter((item) => {
          return item.name.toLowerCase().includes(query.toLowerCase())
        })
        action.options = list
      } else {
        action.options = action.list
      }
    }
  }
  const getGiftList = async()=>{
    action.loading = true
    if(props.externalApi) {
      $emit('getList')
      return
    }
    const res = await propApi.getGifts({page:1,limit:99999,gift_type:props.gift_type})
    action.loading = false
    const { data=[], total=0 } = res.data
    if(total == 0) action.getState = true
    action.options = data
    action.list = data
  }
  const setList = (list:any = [])=>{
    action.loading = false
    action.options = list
    action.list = list
  }
  const selectChange = (gift_id:any='')=>{
    if(gift_id == 'clear') {
      emitQuery(
        '',
        {
          gift_id:0, gift_name:'', price:0
        },
        ''
      )
      return
    }
    if(gift_id) {
      const obj = action.options.find(res=>res.gift_id == gift_id)
      const { image='' } = obj
      emitQuery(gift_id,obj,image)
    }
  }
  // table表格选中礼物
  const handleSelected = (row:any = {})=>{
    const { image='', gift_id:id } = row
    if(!id) return ToastWarning('缺少礼物ID')
    emitQuery(id,row,image)
  }
  /**
   * 
   * @param id 礼物id
   * @param gift_info 礼物详情 
   * @param image 礼物图片
   */
  const emitQuery = (id:number | string = '', gift_info:any = {}, image:string = '' )=>{
    const { gift_name='' } = gift_info
    $emit('update:gift_id',id)
    $emit('update:gift_info',gift_info)
    $emit('update:gift_image',image)
    action.gift_name = gift_name
    if(action.dialogFormVisible) {
      action.total = 0
      action.list = []
      Object.assign(listQuery,{...initialQuyer})
      action.dialogFormVisible = false
    }
  }
  const removeQuery = ()=>{
    action.options = []
    action.list = []
    selectChange('clear')
  }
  const openSerachGift = async(show:Boolean = true)=>{
    action.giftClassifyList = giftClassifyList.filter(res=>{
      const { type='' } = res
      if(props.show_gift_type.indexOf(type) > -1) return res
    })
    const { gift_id } = props
    if(gift_id) {
      listQuery.gift_id = gift_id
      await newGetList()
      const name = action.list.find(res=>res.gift_id == gift_id)?.name || { name:'' }
      action.gift_name = name
    }
    if(show) action.dialogFormVisible = true
  }
  const handleSerach = ()=>{
    listQuery.page = 1
    newGetList()
  }
  const newGetList = async()=>{
    const res = await propApi.getGifts(listQuery)
    action.loading = false
    const { data=[], total } = res.data
    if(total == 0) action.getState = true
    action.total = total
    action.list = data
  }
  defineExpose({
    setList,
    removeQuery
  })
</script>

<template>
  <el-select
    v-if="version == '0.0.0'"
    v-model="gift_id"
    filterable
    remote
    placeholder="请选择礼物"
    clearable
    :remote-method="remoteMethod"
    :loading="action.loading"
    @change="selectChange"
    @clear="selectChange('clear')">
    <el-option
      :label="item.name"
      :value="item.gift_id"
      v-for="(item, index) in action.options"
      :key="index"/>
  </el-select>

  <div v-if="version == '0.0.1'">
    <el-button v-if="!gift_id" type="primary" @click="openSerachGift()">搜索礼物</el-button>
    <el-tag v-if="gift_id" size="large">
      <span style="font-size: 14px;">礼物ID：{{gift_id}} 礼物名称：{{ action.gift_name }}</span>
      <span class="pointer xm-ml10" style="color:blue; font-size: 14px;" @click="openSerachGift()">重新选择</span>
    </el-tag>
    <el-dialog
    top="10vh"
    class="xm-dialog serachGiftBox"
    v-model="action.dialogFormVisible"
    width="60%">
    <div class="xm-headTab">
      <div class="labelBox">
        <div class="labelItem">
          <div class="label">礼物ID：</div>
          <el-input :validate-event="false" v-model="listQuery.gift_id" placeholder="请输入礼物ID"/>
        </div>
        <div class="labelItem">
          <div class="label">礼物名称：</div>
          <el-input :validate-event="false" v-model="listQuery.gift_name" placeholder="请输入礼物名称"/>
        </div>
        <div class="labelItem">
          <div class="label">礼物类型：</div>
          <el-select :validate-event="false" v-model="listQuery.gift_type" placeholder="请选择礼物类型">
            <el-option
              v-for="item in action.giftClassifyList"
              :label="item.label"
              :value="item.type"
            />
          </el-select>
        </div>
        <div class="labelItem">
          <el-button type="primary" @click="handleSerach">查询</el-button>
        </div>
      </div>
    </div>
    <el-table
      class="xm-main xm-TableCenter"
      :data="action.list"
      border
    >
      <el-table-column fixed="left" width="100" prop="gift_id" label="礼物ID" />
      <el-table-column fixed="left" min-width="120" prop="name" label="礼物名称" />
      <el-table-column width="140" prop="image" label="礼物图片">
        <template #default="scoped">
          <xmImage :src="scoped.row.image" :list="[scoped.row.image]" />
        </template>
      </el-table-column>
      <el-table-column width="140" prop="gift_type" label="礼物类型">
        <template #default="scoped">
          {{ giftClassifyList.find(res=>res.type == scoped.row.gift_type)?.label || scoped.row.gift_type }}
        </template>
      </el-table-column>
      <el-table-column min-width="120" sortable prop="price" label="价格" />
      <el-table-column min-width="120" sortable prop="wealth_num" label="富豪值" />
      <el-table-column width="100" prop="is_show" label="是否显示">
        <template #default="scoped">
          <div>
            <el-icon>
              <SuccessFilled v-if="scoped.row.is_show == 1" style="color: #67C23A;" />
              <CircleCloseFilled v-if="scoped.row.is_show == 0" style="clear: #F56C6C;" />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="140" fixed="right" label="操作">
        <template #default="scoped">
          <el-button v-if="gift_id != scoped.row.gift_id" type="primary" @click="handleSelected(scoped.row)">选择礼物</el-button>
          <el-button v-else type="danger" @click="selectChange('clear')">取消选中</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-show="action.total > 0" :total="action.total" v-model:page="listQuery.page"
      v-model:limit="listQuery.limit" @pagination="getGiftList" />
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
  :deep(.serachGiftBox) {
    padding: 0;
    .el-input__wrapper, .el-select__wrapper {
      --el-color-danger:var(--el-border-color);
    }
  }
</style>